<template>
    <div>
      <h2>个人资料</h2>
      <el-form :model="userInfo" label-width="120px">
        <div class="form-row">
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" disabled />
          </el-form-item>
          <el-form-item label="角色">
            <el-input v-model="roleLabel" disabled />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="手机号">
            <el-input v-model="userInfo.userphone" />
          </el-form-item>
          <el-form-item label="性别">
            <el-input v-model="userInfo.sex" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="地址">
            <el-input v-model="userInfo.useraddress" />
          </el-form-item>
          <el-form-item label="别名">
            <el-input v-model="userInfo.nickname" />
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="注册时间">
            <el-input v-model="formattedCreateTime" disabled />
          </el-form-item>
          <el-form-item label="最后更新时间">
            <el-input v-model="formattedUpdateTime" disabled />
          </el-form-item>
        </div>
  
        <div class="avatar-section">
          <h3>用户头像</h3>
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-change="handleChange"
            :before-upload="beforeUpload"
          >
            <img 
              v-if="previewImage"
              :src="previewImage" 
              class="avatar" 
              alt="头像" 
            />
            <el-button v-else style="margin-top: 30px;">上传头像</el-button>
          </el-upload>

        </div>
  
        <el-button type="primary" @click="updateUserInfo">确认修改</el-button>
      </el-form>
    </div>
  </template>
  
  <script>
  import { userInfoService, userInfoUpdateService } from '@/api/user';
  import defaultAvatar from '@/assets/avatar/avatar.jpg';
  import axios from 'axios';
  
  export default {
    data() {
      return {
        userInfo: {
          username: '',
          userphone: '',
          sex: null,
          useraddress: null,
          nickname: null,
          role: 'USER',
          createTime: '',
          updateTime: '',
          userphoto: ''
        },
        previewImage: '',
        selectedFile: null,
        defaultAvatar
      }
    },
    computed: {
      roleLabel() {
        return this.userInfo.role === 'ADMIN' ? '管理员' : '用户';
      },
      formattedCreateTime() {
        return new Date(this.userInfo.createTime).toLocaleString();
      },
      formattedUpdateTime() {
        return new Date(this.userInfo.updateTime).toLocaleString();
      }
    },
    created() {
      this.fetchUserInfo();
    },
    methods: {
      async fetchUserInfo() {
        const response = await userInfoService();
        this.userInfo = response.data;
      },
      async updateUserInfo() {
        await userInfoUpdateService(this.userInfo);
        this.$message.success('个人信息更新成功');
      },
      handleChange(file) {
        this.selectedFile = file.raw; // 保存用户选择的文件
        const reader = new FileReader();
        reader.readAsDataURL(file.raw); // 读取文件为 Data URL
        reader.onload = () => {
          this.previewImage = reader.result; // 设置预览图像的 URL
        };
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt5M = file.size / 1024 / 1024 < 5;
  
        if (!isJpgOrPng) {
          this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        }
        if (!isLt5M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
  
        return isJpgOrPng && isLt5M;
      },
      async submitAvatarUpload() {
        if (!this.selectedFile) {
          this.$message.error('请先选择头像文件!');
          return;
        }
  
        const formData = new FormData();
        formData.append('file', this.selectedFile); // 将文件添加到 FormData
  
        try {
          const response = await axios.post('/api/upload-avatar', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });
          this.userInfo.userphoto = response.data.url; 
          this.$message.success('头像上传成功');
        } catch (error) {
          this.$message.error('头像上传失败');
        }
      }
    }
  }
  </script>
  
  <style scoped>
  .form-row {
    display: flex;
  }
  .form-row .el-form-item {
    flex: 1;
    margin-right: 20px;
  }
  .form-row .el-form-item:last-child {
    margin-right: 0;
  }
  .avatar-section {
    margin-top: 20px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    margin-bottom: 10px;
  }
  .avatar-uploader {
    display: inline-block;
    width: 100px; /* 固定宽度 */
    height: 100px; /* 固定高度 */
    border: 1px dashed #dcdfe6; /* 头像上传框 */
    border-radius: 50%; /* 圆形 */
    overflow: hidden; /* 避免内容溢出 */
    position: relative;
    cursor: pointer;
  }
  </style>
  